package com.csun.cmny.security.core.authentication;

import com.alibaba.fastjson.JSONObject;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2020-10-22 17:52
 * @Description:
 */
public class HuaLongAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    /**
     * Authenticate authentication.
     *
     * @param authentication the authentication
     *
     * @return the authentication
     *
     * @throws AuthenticationException the authentication exception
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        HuaLongAuthenticationToken authenticationToken = (HuaLongAuthenticationToken) authentication;

        String account = (String) authenticationToken.getPrincipal();
        String password = (String) authenticationToken.getCredentials();
        String role = (String) authenticationToken.getRole();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "hualong");
        jsonObject.put("account", account);
        jsonObject.put("password", password);
        jsonObject.put("role", role);
        String jsonStr = JSONObject.toJSONString(jsonObject);

        UserDetails user = userDetailsService.loadUserByUsername(jsonStr);

        if (user == null) {
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }

        HuaLongAuthenticationToken authenticationResult = new HuaLongAuthenticationToken(user, password, role, user.getAuthorities());

        authenticationResult.setDetails(authenticationToken.getDetails());

        return authenticationResult;
    }

    /**
     * Supports boolean.
     *
     * @param authentication the authentication
     *
     * @return the boolean
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return HuaLongAuthenticationToken.class.isAssignableFrom(authentication);
    }

    /**
     * Gets user details service.
     *
     * @return the user details service
     */
    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    /**
     * Sets user details service.
     *
     * @param userDetailsService the user details service
     */
    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}
